package livesun.justiceeternal.base;

import android.app.Activity;
import android.app.Application;
import android.content.ComponentCallbacks;
import android.content.Context;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;

import com.tencent.bugly.Bugly;
import com.tencent.bugly.BuglyStrategy;
import com.tencent.bugly.beta.Beta;
import com.tencent.smtt.sdk.QbSdk;

import livesun.justiceeternal.MainActivity;
import livesun.justiceeternal.R;
import livesun.justiceeternal.db.love.LoveModule;

/**
 * Created by 29028 on 2017/8/11.
 */

public class JEApp extends Application implements Application.ActivityLifecycleCallbacks {
    // 线程通信
    private static Handler handler;
    // 主线程
    private static Thread mainThread;
    // 主线程id
    private static int mainThreadId;
    private static Context context;

    public static Context getInstance() {
        return context;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = this.getApplicationContext();
        handler = new Handler();
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid(); registerActivityLifecycleCallbacks(this);
        LoveModule.getInstance().startLoader();
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
                Log.d("app", " onViewInitFinished is " + arg0);
            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub
            }
        };
        //x5内核初始化接口
        QbSdk.initX5Environment(getApplicationContext(),  cb);

        //Bugly初始化
        checkeUpdate();
    }

    public static Context getContext(){
        return context;
    }
    public static Handler getHandler() {
        return handler;
    }

    public static Thread getMainThread() {
        return mainThread;
    }
    public static int getMainThreadId() {
        return mainThreadId;
    }

    /**
     * 腾讯BugLy的上报异常 和 app更新
     */

    public void checkeUpdate(){

        /***** Beta高级设置 *****/
        /**
         * true表示app启动自动初始化升级模块; false不会自动初始化;
         * 开发者如果担心sdk初始化影响app启动速度，可以设置为false，
         * 在后面某个时刻手动调用Beta.init(getApplicationContext(),false);
         */
        Beta.autoInit = true;

        /**
         * true表示初始化时自动检查升级; false表示不会自动检查升级,需要手动调用Beta.checkUpgrade()方法;
         */
        Beta.autoCheckUpgrade = true;

        /**
         * 设置升级检查周期为60s(默认检查周期为0s)，60s内SDK不重复向后台请求策略);
         */
//        Beta.upgradeCheckPeriod = 2 * 1000;
        /**
         * 设置启动延时为1s（默认延时3s），APP启动1s后初始化SDK，避免影响APP启动速度;
         */
        Beta.initDelay = 1 * 1000;
        /**
         * 设置通知栏大图标，largeIconId为项目中的图片资源;
         */
        Beta.largeIconId = R.mipmap.app_icon;
        /**
         * 设置状态栏小图标，smallIconId为项目中的图片资源Id;
         */
        Beta.smallIconId = R.mipmap.app_icon;
        /**
         * 设置更新弹窗默认展示的banner，defaultBannerId为项目中的图片资源Id;
         * 当后台配置的banner拉取失败时显示此banner，默认不设置则展示“loading“;
         */
        Beta.defaultBannerId = R.mipmap.app_icon;
        /**
         * 设置sd卡的Download为更新资源保存目录;
         * 后续更新资源会保存在此目录，需要在manifest中添加WRITE_EXTERNAL_STORAGE权限;
         */
        Beta.storageDir = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
        /**
         * 已经确认过的弹窗在APP下次启动自动检查更新时会再次显示;
         */
        Beta.showInterruptedStrategy = true;
        /**
         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗; 不设置会默认所有activity都可以显示弹窗;
         */
        Beta.canShowUpgradeActs.add(MainActivity.class);

        /***** Bugly高级设置 *****/
        BuglyStrategy strategy = new BuglyStrategy();
        /**
         * 设置app渠道号
         strategy.setAppChannel(APP_CHANNEL);*/

//        自定义Ui
        Beta.upgradeDialogLayoutId = R.layout.update_dialog;

        /***** 统一初始化Bugly产品，包含Beta *****/
        Bugly.init(getApplicationContext(), "c7ef9c6182", true,strategy);

    }


    private static float sNonCompateDensity;
    private static float sNonoCompateScaledDensity;
    //    比如以分辨率1920px * 1080px来设计，以density为3来标注，也就是屏幕其实是640dp * 360dp
    private static final int sSesignSize = 360;

    //px = density * dp;
    //density = dpi / 160;
    //px = dp * (dpi / 160);
    public void setCustomDensity(@Nullable final Application context, Activity activity) {
        DisplayMetrics appDisplayMetrics = context.getResources().getDisplayMetrics();
        if (sNonCompateDensity == 0) {
            sNonCompateDensity = appDisplayMetrics.density;
            sNonoCompateScaledDensity = appDisplayMetrics.scaledDensity;
            context.registerComponentCallbacks(new ComponentCallbacks() {
                @Override
                public void onConfigurationChanged(Configuration newConfig) {
                    if (newConfig != null && newConfig.fontScale > 0) {
                        //切换字体的回调
                        sNonoCompateScaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
                    }
                }

                @Override
                public void onLowMemory() {

                }
            });
        }
        float tagretDensity = appDisplayMetrics.widthPixels / sSesignSize;
        int tagretDensityDpi = (int) (160 * tagretDensity);
        //用来计算字体大小
        float tagretScaleDensity = tagretDensity * (sNonoCompateScaledDensity / sNonCompateDensity);
        appDisplayMetrics.density = tagretDensity;
        appDisplayMetrics.densityDpi = tagretDensityDpi;
        appDisplayMetrics.scaledDensity = tagretScaleDensity;

        DisplayMetrics activityDisplayMetrics = activity.getResources().getDisplayMetrics();
        activityDisplayMetrics.density = tagretDensity;
        activityDisplayMetrics.densityDpi = tagretDensityDpi;
        activityDisplayMetrics.scaledDensity = tagretScaleDensity;
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        setCustomDensity(this, activity);
    }

    @Override
    public void onActivityStarted(Activity activity) {

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }
}
